# -*- coding:utf-8 -*-
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.http.response import JsonResponse, HttpResponse
from callcentre.models import TMobileTyping
from django.conf import settings
from django.contrib.auth import get_user_model

User = get_user_model()


@csrf_exempt
def receive(request, *args, **kwargs):
    if request.method != 'POST':
        return HttpResponse('method error.')

    client_ip = request.META['REMOTE_ADDR']
    username = request.POST.get('u')
    mobile = request.POST.get('m')
    note = request.POST.get('d')
    try:
        user = User.objects.get(username=username)
    except Exception as e:
        return HttpResponse('user error.')

    try:
        obj, created = TMobileTyping.objects.get_or_create(
            mobile=mobile, defaults={'note': note, 'client_ip': client_ip,
                                     'name': username, 'create_user': username
                                     })
    except Exception as e:
        created = None

    if created:
        return HttpResponse('ok')

    return HttpResponse('duplicate mobile.')
